package com.blog.utils;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

public class SessionUtil {

	// public static HttpSession session = ServletActionContext.getRequest()
	// .getSession();

	/**
	 * 获取Session
	 * 
	 * @return
	 */
	public static HttpSession getSession() {
		return ServletActionContext.getRequest().getSession();
	}

	/**
	 * 根据名称获取Session值
	 * 
	 * @param name
	 * @return
	 */
	public static Object getAttribute(String name) {
		return ServletActionContext.getRequest().getSession()
				.getAttribute(name);
	}

	/**
	 * 根据名称获取Session值
	 * 
	 * @param name
	 * @return
	 */
	public static String getString(String name) {
		return (String) ServletActionContext.getRequest().getSession()
				.getAttribute(name);
	}

	/**
	 * 根据名称设置Session值
	 * 
	 * @param name
	 * @param val
	 */
	public static void setAttribute(String name, Object val) {
		ServletActionContext.getRequest().getSession().setAttribute(name, val);
	}

	/**
	 * 根据名称设置Session如果存在同名Session并判断是否刷新Session值
	 * 
	 * @param name
	 * @param val
	 * @param refresh
	 */
	public static void setAttribute(String name, Object val, boolean refresh) {
		HttpSession session = ServletActionContext.getRequest().getSession();
		if (CommonUtil.isEmpty(session.getAttribute(name))) {
			session.setAttribute(name, val);
		} else {
			if (refresh) {
				session.setAttribute(name, val);
			}
		}
	}

	/**
	 * 根据名称Sessionkey删除Session标识
	 * 
	 * @param name
	 */
	public static void removeAttribute(String name) {
		ServletActionContext.getRequest().getSession().removeAttribute(name);
	}

	/**
	 * 删除所有Session标识
	 */
	public static void removeAttributes() {
		HttpSession session = ServletActionContext.getRequest().getSession();
		Enumeration<?> e = session.getAttributeNames();
		while (e.hasMoreElements()) {
			String name = (String) e.nextElement();
			session.removeAttribute(name);
		}
	}

	/**
	 * 使当前Session无效
	 */
	public static void invalidate() {
		ServletActionContext.getRequest().getSession().invalidate();
	}

	/**
	 * 设置FormSessionKey
	 * 
	 * @param request
	 */
	public static void setFormSessionKey(HttpServletRequest request) {
		request.getSession().setAttribute(ConstantUtil.FORM_SESSION_KEY,
				MD5.encrypt(Math.random() + ""));
	}

	/**
	 * 比较FormSessionKey是否相同
	 * 
	 * @param request
	 * @param formSessionKey
	 * @return
	 */
	public static boolean compareFormSessionKey(HttpServletRequest request,
			String formSessionKey) {
		if (null != request && null != request.getSession() 
				&& null != request.getSession().getAttribute(ConstantUtil.FORM_SESSION_KEY)) {
			String key = (String) request.getSession().getAttribute(ConstantUtil.FORM_SESSION_KEY);
			return key.equals(formSessionKey);
		}
		return false;
	}
}
